import cv2
from PIL import Image
# coding=utf-8
import os
import os.path
import numpy as np
import cv2


# 读取原始的图像
def rotate_bound(image, angle):
    # grab the dimensions of the image and then determine the
    # center
    (h, w) = image.shape[:2]
    (cX, cY) = (w // 2, h // 2)
    # grab the rotation matrix (applying the negative of the
    # angle to rotate clockwise), then grab the sine and cosine
    # (i.e., the rotation components of the matrix)
    M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])
    # compute the new bounding dimensions of the image
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))
    # adjust the rotation matrix to take into account translation
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY
    # perform the actual rotation and return the image
    newimg = cv2.warpAffine(image, M, (nW, nH))
    cv2.normalize(newimg, newimg, 0, 255, cv2.NORM_MINMAX)
    return newimg


def gettrain():
    # dict = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H", 9: "I", 10: "J", 11: "K", 12: "L", 13: "M"}
    filename = 'train/test.txt'
    k = 0
    for j in range(1, 11):
        for i in np.arange(-180, 180, 0.06):
            img = cv2.imread("train/template_train/" + str(j) + ".jpg")
            img = rotate_bound(img, -i)
            # cv2.imshow("after",img)
            img = cv2.resize(img, (28, 28))
            newfilename = str(k) + "_" + str(j - 1) + ".jpg"
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            cv2.imwrite("train/mypic/" + newfilename, img)
            k = k + 1
            # cv2.waitKey(0)
            # cv2.destroyAllWindows()
            with open(filename, "a") as f:
                f.write(newfilename + " " + str(j - 1) + "\n")
                f.close()


def gettest():
    # dict = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H", 9: "I", 10: "J", 11: "K", 12: "L", 13: "M"}
    filename = 'test/test.txt'
    k = 0
    for j in range(1, 11):
        for i in np.arange(-180, 180, 0.36):
            img = cv2.imread("test/template_test/" + str(j) + ".jpg")
            img = rotate_bound(img, -i)
            # cv2.imshow("after",img)
            img = cv2.resize(img, (28, 28))
            newfilename = str(k) + "_" + str(j - 1) + ".jpg"
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            cv2.imwrite("test/mypic/" + newfilename, img)
            # cv2.waitKey(0)
            # cv2.destroyAllWindows()
            k = k + 1
            with open(filename, "a") as f:
                f.write(newfilename + " " + str(j - 1) + "\n")
                f.close()


def is_color_image(url):
    im = Image.open(url)
    pix = im.convert('RGB')
    width = im.size[0]
    height = im.size[1]
    oimage_color_type = "Grey Image"
    is_color = []
    for x in range(width):
        for y in range(height):
            r, g, b = pix.getpixel((x, y))
            r = int(r)
            g = int(g)
            b = int(b)
            if (r == g) and (g == b):
                pass
            else:
                oimage_color_type = 'Color Image'
    return oimage_color_type


def rgbtogray():
    for filename in os.listdir("train/mypic"):
        if filename.endswith('jpg'):
            img = cv2.imread("train/mypic/" + filename)
            # img = rotate_bound(img, 90)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            cv2.imwrite("train/mypic/" + filename, img)


if __name__ == '__main__':
    gettrain()
    gettest()
